package com.demo.websocket;

import com.demo.core.exception.ParameterException;
import com.demo.dao.CommentDao;
import com.demo.dao.PostDao;
import com.demo.dao.RegistrationInformationDao;
import com.demo.dao.ReplyDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyThread implements Runnable {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private ReplyDao replyDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private PostDao postDao;

    @Autowired
    private RegistrationInformationDao registrationInformationDao;

    private boolean stopMe = true;

    private ThreadLocal<Long> userIdThreadLocal = new ThreadLocal<>();

    public void stopMe() {
        stopMe = false;
    }

    @Override
    public void run() {
        WebSocketServer wbs = new WebSocketServer();
        while (stopMe) {
            Long userId = userIdThreadLocal.get(); // 获取用户ID
            if (userId != null) {
                if (checkForNewMessages(userId)) {
                    eventPublisher.publishEvent(new NewMessageEvent(this, userId));
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean checkForNewMessages(Long uid) {
        //查询未读信息个数
        int replyCount = replyDao.countNotViewReply(uid);
        List<Long> pids = postDao.selectPidByuid(uid);
        int commentCount = 0;
        for (Long pid : pids) {
            commentCount += commentDao.countNotViewComment(pid);
        }
        boolean hasNotRead = registrationInformationDao.countNotViewRegistration(uid) + replyCount + commentCount > 0;
        return hasNotRead;
    }

    // 在适当的地方设置用户ID到ThreadLocal中
    public void setUserId(Long userId) {
        userIdThreadLocal.set(userId);
    }

    // 在适当的地方清除ThreadLocal中的用户ID
    public void clearUserId() {
        userIdThreadLocal.remove();
    }
}
